

const app = getApp();
Page({
    data: { showMsg: false, focus: true },
    onLoad: function (options) {
        this.setData({
            history: wx.getStorageSync('searchHistory')
        })
        app.http.get('goods/recommend').then(res => {
            this.setData({
                recommend: res.data.items
            })
        }).catch(err => {

        })
    },
    onFocus() {
        this.setData({ focus: true });
    },
    onBlur() {
        this.setData({ focus: false });
    },
    search(evt) {
        var content = evt.detail.value;
        if (!content) { return };
        this.init();
        this.setData({
            content: content,
        });
        if (content) {
            this.loadData();
        }
    },

    init() {
        this.setData({
            page: 1,
            totalPage: 2,
            list: [],
        });
    },

    doSearch() {
        this.init();
        this.loadData();
    },

    clickHistory(evt) {
        this.init();
        this.setData({ content: evt.currentTarget.dataset.content });
        this.loadData();
    },
    clearHistory() {
        this.setData({
            history: [],
        })
        wx.removeStorageSync('searchHistory');
    },

    clear() {
        this.setData({ content: "" });
    },

    onInput(evt) {
        this.setData({ content: evt.detail.value });
    },

    loadData() {
        var history = wx.getStorageSync('searchHistory');
        if (!history) {
            history = [];
        }

        if (history.length > 5) {
            history.shift();
        }
        if (history.indexOf(this.data.content) < 0) {
            history.push(this.data.content);
        }
        wx.setStorageSync('searchHistory', history);
        this.setData({
            history: history
        })
        if (this.data.page > this.data.totalPage || this.data.loading) {
            return;
        }
        console.log(11111);
        this.setData({ loading: true });
        app.http.get('goods/search', {
            data: { keywords: this.data.content, page: this.data.page },
            requireLogin: false,
        }).then(res => {
            this.setData({ loading: false, showMsg: true });
            if (!res.data) {
                return;
            }
            var list = this.data.list.concat(res.data.items);
            this.setData({ list: list, totalPage: res.data.total, loading: false, page: this.data.page + 1 });
        })
    },

    onReachBottom() {
        if (this.data.content) {
            this.loadData();
        }
    }
})